<template>
	<ls-skeleton :loading="loading">
		<!-- 产品信息 -->
		<view class="product-section">
			<block v-if="list.length > 0">
				<view class="product-list">
					<!-- 遍历商品列表 -->
					<view class="product-item" v-for="(item, index) in list" :key="index">
						<!-- 商品图片 @click="previewImage(item.productImage)"-->
						<image class="product-image" @click="goToSeriesDetail(item.categoryId)" :src="item.productImage"
							mode="aspectFill"></image>
						<view class="product-info">
							<!-- 查看系列规格按钮 -->
							<!-- 	<navigator
								:url="'/pages/goods/goods_detail/index?productId='+item.categoryId + '&type=STORE'"
								class="view-series-btn" hover-class="none">
								系列详情
							</navigator> -->
							<!-- 商品名称和规格 -->
							<!-- <view class="product-name">{{ item.productName }} - {{ item.specifications }}</view> -->
							<view class="product-name">{{ truncate(item.productName, 15) }}</view>

							<!-- 产品信息 -->
							<view class="product-detail">
								<view class="separator-line"></view>
								<view class="product-detail-info">
									<view class="product-detail-row">
										<view class="product-detail-item">
											<view class="product-detail-text">{{truncate(item.specifications||"暂无", 4)}}
											</view>
											<view class="product-detail-label">系列</view>
										</view>
										<view class="product-detail-item">
											<view class="product-detail-text">{{item.usePower||"暂无"}}</view>
											<view class="product-detail-label">功率</view>
										</view>
										<view class="product-detail-item">
											<view class="product-detail-text">{{item.rightFlux||"暂无"}}</view>
											<view class="product-detail-label">流明值</view>
										</view>

									</view>
								</view>
								<view class="separator-line"></view>
							</view>

							<!-- 加入购物车按钮 -->
							<view class="car-buttons">

								<!-- 加减组件 -->
								<view class="quantity-selector">
									<!-- 商品价格 v-if=" userType == 'STORE'||(userType == 'SALE'&&!isSale)"v-if="isSale"-->
									<view class="product-price" v-if=" userType == 'STORE'&&isLogin">
										￥{{(item.proxyPrice || 0).toFixed(2)}}</view>
									<view class="product-price" v-if="userType == 'CAR'||!isLogin">
										￥{{(item.salePrice||0).toFixed(2)}}</view>
									<view class="product-price" v-if="userType=='SALE'&&isLogin">
										￥{{(item.productPrice||0).toFixed(2)}}</view>

									<button class="decrease-btn" @click.stop="updateCart(item, -1)">-</button>
									<view class="quantity">{{ cart[item.proDetailId] || 0 }}</view>
									<button class="increase-btn" @click.stop="updateCart(item, 1)">+</button>
								</view>
							</view>
						</view>
					</view>
				</view>
			</block>
			<!-- 无产品时的占位 -->
			<u-empty v-else mode="favor" icon="../../../../static/images/list.png" text="暂无产品" width="320" height="320"
				textSize="24"></u-empty>
		</view>


		<!-- 门店 -->
		<!-- 		<view class="footer flex-row row-between-wrapper" v-if="userType == 'STORE' && type == 'STORE'"> -->
		<view class="footer flex-row row-between-wrapper">
			<!-- <navigator hover-class="none" class="item skeleton-rect" open-type="switchTab" url="/pages/index/index">
				<view class="iconfont icon-shouye6"></view>
				<view class="p_center">首页</view>
			</navigator>
			<view @click="setCollect" class="item skeleton-rect">
				<view class="iconfont icon-kefu"></view>
				<view class="p_center">客服</view>
			</view> -->

			<view class="animated item skeleton-rect" :class="animated == true ? 'bounceIn' : ''" @click="goCart">
				<view class="iconfont icon-gouwuche1">
					<text class="num bg-color" v-if="parseInt(CartCount) > 0">{{CartCount || 0}}</text>
				</view>
				<view class="p_center skeleton-rect">购物车</view>
			</view>
			<!-- 总价部分 -->
			<view class="flex-column">
				<!-- 总价部分 -->
				<view class="total-price">
					<text style="font-size: 30rpx;">合计：</text>
					<text class="price">
						￥
						<text class="price-before">{{ Math.floor(totalPrice) }}.</text>
						<text class="price-after">{{ (totalPrice % 1).toFixed(2).slice(2) }}</text>
					</text>
				</view>

				<!-- 已选商品部分 -->
				<view class="selected-items">
					<text class="items-text">共：{{ selectedCount }} 件</text>
				</view>
			</view>



			<view class="bnt flex-row skeleton-rect">
				<form @submit="joinCart" class="joinCart bnts">
					<button class="joinCart bnts" form-type="submit">
						加入购物车
					</button>
				</form>
			</view>
		</view>

		<productWindow :attr="attr" :isShow="0" :iSplus="1" @myevent="onMyEvent" @ChangeAttr="ChangeAttr"
			@ChangeCartNum="ChangeCartNum" @attrVal="attrVal" @iptCartNum="iptCartNum" id="product-window"
			@getImg="showImg"></productWindow>
		<!-- <view>
				<view class="bnt flex-row skeleton-rect">
					<form @submit="joinCart" class="joinCart bnts">
						<button class="joinCart bnts" form-type="submit">
							加入购物车
						</button>
					</form>
					<form @submit="goBuy" class="buy bnts">
						<button class="buy bnts" form-type="submit">
							立即购买
						</button>
					</form>
				</view>
			</view> -->

		<!-- 批发商 -->
		<!-- <view class="footer flex-row row-between-wrapper" v-if="userType == 'SALE' && type == 'SALE'">
			<navigator hover-class="none" class="item skeleton-rect" open-type="switchTab" url="/pages/index/index">
				<view class="iconfont icon-shouye6"></view>
				<view class="p_center">首页</view>
			</navigator>
			<view @click="setCollect" class="item skeleton-rect">
				<view class="iconfont icon-kefu"></view>
				<view class="p_center">客服</view>
			</view>

			<view class="animated item skeleton-rect" :class="animated == true ? 'bounceIn' : ''" @click="goCart">
				<view class="iconfont icon-gouwuche1">
					<text class="num bg-color" v-if="parseInt(CartCount) > 0">{{
		  CartCount || 0
		}}</text>
				</view>
				<view class="p_center skeleton-rect">购物车</view>
			</view>
			<view class="bnt flex-row skeleton-rect">
				<form @submit="joinCart" class="joinCart bnts">
					<button class="joinCart bnts" form-type="submit">
						加入购物车
					</button>
				</form>
			</view> -->
		<!-- 			<view>
				<view class="bnt flex-row skeleton-rect">
					<form @submit="joinCart" class="joinCart bnts">
						<button class="joinCart bnts" form-type="submit">
							加入购物车
						</button>
					</form>
					<form @submit="goBuy" class="buy bnts">
						<button class="buy bnts" form-type="submit">
							立即购买
						</button>
					</form>
				</view>
			</view> -->



	</ls-skeleton>
</template>

<script>
	import {
		mapGetters
	} from "vuex";
	import {
		toLogin
	} from "@/libs/login.js";
	import {
		getList
	} from '@/api/product.js';
	import {
		saveInvite,
		getUserInfo
	} from '@/api/user.js';
	import {
		getUserCar,
		addToCar
	} from "@/api/order.js";
	export default {
		data() {
			return {
				productList: [], // 商品列表
				cart: {}, // 购物车数据，用于存储商品 ID 和数量
				CartCount: 0,
				type: '',
				loading: true,
				list: [], // 产品列表数据
				typeId: null, // 当前类别 ID
				itemName: '', // 当前类别 名称（作为查规格搜索条件）
				isSale: false, //是否从工厂代理进入
			};
		},
		computed: {
			...mapGetters(["isLogin", 'uid', 'userType']),
			selectedCount() {
				return Object.values(this.cart).reduce((sum, count) => sum + count, 0);
			},
			totalPrice() {
				return this.list.reduce((total, item) => {
					const quantity = this.cart[item.proDetailId] || 0;
					if (this.userType == 'STORE' && this.isLogin) { //|| (this.userType == 'SALE' && !this.isSale)
						return total + (quantity * item.proxyPrice);
					} else if (this.userType == 'SALE' && this.isLogin) { // && this.isSale
						return total + (quantity * item.productPrice);
					} else {
						return total + (quantity * item.salePrice);
					}

				}, 0);
			}
		},
		watch: {
			isLogin: {
				handler: function(newV, oldV) {
					if (newV == true) {
						this.getUserCar();
					}
				},
				deep: true,
			},
		},

		onLoad(options) {
			this.typeId = options.typeId;
			this.type = options.type;
			this.itemName = options.itemName;
			if (options.isSale) {
				this.isSale = options.isSale;
			}
			this.fetchProductList();
			this.getUserCar();
		},
		onShow() {
			this.getUserCar();;
		},
		mounted() {
			console.log("userType：" + this.userType);
			console.log("规格名称：" + this.itemName);
			console.log("工厂采购：" + this.isSale);
		},
		methods: {
			goToSeriesDetail(categoryId) {
				const url = `/pages/goods/goods_detail/index?productId=${categoryId}&type=STORE`;
				uni.navigateTo({
					url
				});
			},
			truncate(text, length) {
				if (text.length > length) {
					return text.substring(0, length) + '...';
				}
				return text;
			},
			previewImage(imageUrl) {
				wx.previewImage({
					current: imageUrl, // 当前显示图片的http链接
					urls: [imageUrl] // 需要预览的图片http链接列表
				});
			},
			// 更新购物车
			updateCart(item, delta) {
				const productId = item.proDetailId;
				// 当前数量
				const currentQuantity = this.cart[productId] || 0;
				// 计算新数量（最小值为 0）
				const newQuantity = Math.max(0, currentQuantity + delta);
				// 更新购物车数据
				if (newQuantity === 0) {
					this.$delete(this.cart, productId); // 数量为 0 时从购物车中移除
				} else {
					this.$set(this.cart, productId, newQuantity);
				}

				// 处理购物车操作（如同步到后端）
				this.syncCartToBackend(item, newQuantity);
			},
			// 同步购物车数据到后端
			syncCartToBackend(item, quantity) {
				console.log(`商品ID: ${item.proDetailId}, 数量: ${quantity}`);
				// 模拟同步逻辑，可以替换为实际的 API 调用
				// uni.request({...})
			},
			fetchProductList() {
				getList({
						typeId: this.typeId,
						itemName: this.itemName,
					})
					.then(res => {
						if (res && res.value && res.value.list) {
							this.list = res.value.list;
							if (this.list.length === 1) {
								const categoryId = this.list[0].categoryId; // 获取唯一对象的 categoryId
								const url = `/pages/goods/goods_detail/index?productId=${categoryId}&type=STORE`;
								uni.navigateTo({
									url: url,
								});
							}
						} else {
							this.list = [];
						}
					})
					.catch(err => {
						this.list = [];
						this.$util.Tips({
							title: err.message || "获取产品列表失败"
						});
					})
					.finally(() => {
						this.loading = false;
					});
			},
			/**
			 * 打开属性加入购物车
			 */
			joinCart: function(e) {
				//是否登录
				if (this.isLogin === false) {
					toLogin();
				} else {
					this.addCart();
				}
			},
			/**
			 * 去购物车
			 */
			goCart() {
				uni.navigateTo({
					url: '/pages/goods/goods_addcart/index'
				});
			},
			/**
			 * 获取用户购物车
			 */
			getUserCar() {
				if (this.isLogin) {
					let that = this;
					getUserCar({
						userInfoId: that.uid
					}).then(res => {
						that.CartCount = res.value.length;
						console.log("that.CartCount=" + that.CartCount)
					}).catch(err => {
						that.$util.Tips({
							title: err
						});
					})
				}
			},
			/*	
			 * 加入购物车
			 */
			addCart() {
				console.log(this.cart); // 打印当前购物车中的内容

				let that = this;

				// 遍历 cart 对象，将每个产品添加到购物车
				for (let proDetailId in this.cart) {
					if (this.cart.hasOwnProperty(proDetailId)) {
						// 获取对应的数量
						let addNumber = this.cart[proDetailId];

						// 调用 addToCar 方法将商品添加到购物车
						addToCar({
								userInfoId: that.uid,
								proDetailId: proDetailId, // 产品规格 ID
								addNumber: addNumber // 对应的数量
							}).then(function(res) {
								// 提示用户添加成功
								that.$util.Tips({
									title: "添加购物车成功",
									success: () => {
										that.getUserCar(true); // 更新购物车
									},
								});
							})
							.catch((err) => {
								that.isOpen = false;
								// 提示错误信息
								return that.$util.Tips({
									title: err,
								});
							});
					}
				}
			}


		}
	};
</script>

<style scoped>
	.product-list {
	  max-height: 87vh; /* 限制最大高度 */
	  overflow-y: auto; /* 启用纵向滚动条 */
	}

	.product-section {
		display: flex;
		flex-direction: column;
		gap: 10px;
		padding: 10px;
	}

	.product-item {
		display: flex;
		flex-direction: row;
		/* 	align-items: center; */
		border: 1px solid #ddd;
		padding: 10rpx;
		border-radius: 8px;
		background-color: #fff;
	}

	.product-image {
		width: 145px;
		height: 145px;
		margin-right: 10px;
		border-radius: 8px;
	}

	.product-info {
		margin-left: 30rpx;
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.product-name {
		font-size: 30rpx;
		font-weight: bold;
	}

	.product-price {
		color: #ff2f2f;
		font-size: 36rpx;
	}

	/* 	.footer .bnt {
		width: 444rpx;
		height: 76rpx;
	} */
	.flex-column {
		display: flex;
		flex-direction: column;
		/* 垂直排列 */
		justify-content: center;
		align-items: center;
		/* 居中 */
	}

	.footer .bnt .bnts {
		width: 222rpx;
		text-align: center;
		line-height: 76rpx;
		color: #fff;
		font-size: 28rpx;
	}

	.footer .bnt .joinCart {
		border-radius: 50rpx;
		background-color: #00af6f;
		// background-image: linear-gradient(to right, #fea10f 0%, #fa8013 100%);
	}

	.footer .bnt .buy {
		border-radius: 0 50rpx 50rpx 0;
		background-color: #06A972;
		// background-image: linear-gradient(to right, #fa6514 0%, #e93323 100%);
	}

	.footer .item {
		font-size: 18rpx;
		color: #666;
	}

	.footer .item .iconfont {
		text-align: center;
		font-size: 40rpx;
		height: 55rpx;
	}

	.footer .item .iconfont.icon-shoucang1 {
		color: var(--view-theme);
	}

	.footer .item .iconfont.icon-gouwuche1 {
		font-size: 40rpx;
		position: relative;
	}

	.footer .item .iconfont.icon-gouwuche1 .num {
		color: #fff;
		position: absolute;
		font-size: 16rpx;
		padding: 2rpx 12rpx 2rpx;
		border-radius: 200rpx;
		top: -5rpx;
		right: -10rpx;
	}

	.footer {
		position: absolute;
		bottom: 0;
		width: 100%;
		box-sizing: border-box;
		background-color: #fff;
		z-index: 277;
		border-top: 1rpx solid #f0f0f0;
		height: 100rpx;
		height: calc(100rpx + constant(safe-area-inset-bottom)); ///兼容 IOS<11.2/
		height: calc(100rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/
	}

	.total-price {
		display: flex;
		align-items: flex-end;
		font-size: 36rpx;
		font-weight: bold;
		color: #FF6A00;
		/* 橘色 */
	}

	.price {
		font-size: 36rpx;
		font-weight: bold;
		color: #FF6A00;
		/* 橘色 */
	}

	.price-before {
		font-size: 42rpx;
		/* 整数部分字体大一些 */
		margin-right: 4rpx;
	}


	.price-after {
		font-size: 30rpx;
		/* 小数部分字体较小 */
		color: #FF6A00;
	}

	.selected-items {
		margin-top: 10rpx;
		font-size: 28rpx;
		color: #666;
	}

	//系列详情
	.action-buttons {
		display: flex;
		flex-direction: column;
		/* 垂直布局 */
		align-items: center;
		/* 水平居中 */
		gap: 20rpx;
		/* 子元素之间的间距 */
	}

	.view-series-btn {
		font-size: 26rpx;
		color: #007aff;
		/* 蓝色文字，更清晰 */
		text-align: center;
		/* 文本居中 */
		margin-bottom: 10rpx;
		/* 与加减组件的间距 */
	}


	//+-框
	.quantity-selector {
		display: flex;
		align-items: center;
		gap: 10rpx;
		/* 小程序中的间距单位 */
	}

	.decrease-btn,
	.increase-btn {
		background: none;
		/* 去掉背景色 */
		color: #333;
		/* 按钮文字颜色 */
		font-size: 28rpx;
		/* 字体大小 */
		font-weight: bold;
		/* 字体加粗 */
	}

	.quantity {
		font-size: 26rpx;
		/* 数字的字体大小 */
		font-weight: bold;
		text-align: center;
		width: 10rpx;
		/* 数字框宽度 */
	}

	//产品信息样式
	.product-detail-container {
		background-color: #fff;
		/* 背景色，可选 */
		padding: 15px 10px;
		/* 内容与边框的间距 */
		border-radius: 10px;
		/* 圆角效果 */
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		/* 阴影提升层次感 */
	}

	.separator-line {
		height: 1px;
		/* 横线高度 */
		background-color: #e0e0e0;
		/* 横线颜色 */
		margin: 10px 0;
		/* 横线的上下间距 */
	}

	.product-detail-info {
		display: flex;
		flex-wrap: wrap;
		/* 自动换行 */
		justify-content: space-between;
		/* 等间距对齐 */
	}

	.product-detail-row {
		display: flex;
		width: 100%;
		/* 每行占满宽度 */
	}

	.product-detail-item {
		flex: 1;
		/* 每个项目平分宽度 */
		text-align: center;
		/* 水平居中 */
		margin-bottom: 10px;
		/* 每行间距 */
	}

	.product-detail-text {
		font-size: 26rpx;
		/* 内容文字大小 */
		display: flex;
		justify-content: center;
		align-items: center;
		/* 水平和垂直居中 */
	}

	.product-detail-label {
		font-size: 20rpx;
		/* 标签文字大小 */
		color: #999;
		/* 标签文字颜色 */
		display: flex;
		justify-content: center;
		align-items: center;
		/* 水平和垂直居中 */
		margin-top: 5px;
		/* 调整标签与内容的间距 */
	}
</style>